package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("登录过滤器>>>");
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        // 1.放行应该直接放行的资源
        String resources[]={
             "/employee/login",//登录
             "/employee/logout",//退出登录
             "/backend",//管理员静态资源
             "/front",//客户端静态资源
                "/user/login",//客户端登录
                "/user/sendMsg",//客户端发送验证码
                "/doc.html",
                "/webjars/",
                "/swagger-resources",
                "/v2/api-docs"

        };
        //获取当前用户的请求路径
        String url = req.getRequestURL().toString();
        for (String resource : resources) {
            if (url.contains(resource)){
                log.info("登录过滤器2>>>");
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
        // 2.判断用户是否登录(session)
        HttpSession session = req.getSession();
        Object emp = session.getAttribute("employee");
        if (emp != null){
            //登陆过了 放行
            Long empId = (Long) req.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            long id = Thread.currentThread().getId();
            log.info("线程id为:{}",id);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //4-2、判断登录状态，如果已登录，则直接放行
        if(req.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",req.getSession().getAttribute("user"));
            //将用户信息储存到BaseContext中
            Long userId = (Long) req.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            //登录放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }


        // 3.资源不直接放行,用户未登录,访问失败,(前端)跳转到登录页面
        //手动返回R对象json字符串给前端ajax(响应拦截器:msg=NOTLOGIN ,code=0)
        /*
        R{
              code:0
              msg:NOTLOGIN
              data:
              }
         */
        servletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

}
